<template>
  <div class="filter-header" :class="{ 'filter-header--mobile': isMobile }">
    <div class="date-picker-wrapper" :class="{ 'date-picker-wrapper--mobile': isMobile }">
      <template v-if="!isMobile">
        <el-date-picker v-if="isRange" v-model="dateRange" :type="isMonthPicker ? 'monthrange' : 'daterange'"
          unlink-panels range-separator="到" :start-placeholder="isMonthPicker ? '起始月份' : '起始日期'"
          :end-placeholder="isMonthPicker ? '结束月份' : '结束日期'" :disabled-date="disabledDate" value-format="x"
          @change="handleDateRangeChange" class="date-picker" :size="size" :style="{ width: width }" />
        <el-date-picker v-else v-model="singleDate" :type="isMonthPicker ? 'month' : 'date'"
          :placeholder="isMonthPicker ? '选择月份' : '选择日期'" value-format="x" :disabled-date="disabledDate"
          @change="handleSingleDateChange" class="date-picker" :size="size" :style="{ width: width }" />
      </template>

      <template v-else>
        <template v-if="isRange">
          <div class="mobile-date-picker">
            <div class="mobile-date-input">
              <el-date-picker :style="{ width: mobileWidth }" v-model="startDate"
                :type="isMonthPicker ? 'month' : 'date'" :placeholder="isMonthPicker ? '起始月份' : '起始日期'"
                :disabled-date="disabledDate" value-format="x" @change="handleMobileStartDateChange" :size="size" />
            </div>
            <span class="separator">到</span>
            <div class="mobile-date-input">
              <el-date-picker :style="{ width: mobileWidth }" v-model="endDate" :type="isMonthPicker ? 'month' : 'date'"
                :placeholder="isMonthPicker ? '结束月份' : '结束日期'" :disabled-date="disabledDate" value-format="x"
                @change="handleMobileEndDateChange" :size="size" />
            </div>
          </div>
        </template>
        <template v-else>
          <el-date-picker v-model="singleDate" :type="isMonthPicker ? 'month' : 'date'"
            :placeholder="isMonthPicker ? '选择月份' : '选择日期'" value-format="x" :disabled-date="disabledDate"
            @change="handleSingleDateChange" class="date-picker" :size="size" :style="{ width: width }" />
        </template>
      </template>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, computed } from "vue";
import dayjs from "dayjs";
import { useMobileDetection } from "@/composables/useMobileDetection";

const props = defineProps({
  modelValue: {
    type: [Array, Number],
    required: true,
  },
  isRange: {
    type: Boolean,
    default: true,
  },
  isMonthPicker: {
    type: Boolean,
    default: false,
  },
  maxDays: {
    type: Number,
    default: 90,
    validator: (value) => value > 0,
  },
  minDays: {
    type: Number,
    default: 0,
    validator: (value) => value >= 0,
  },
  maxDate: {
    type: Number,
    default: null
  },
  minDate: {
    type: Number,
    default: null
  },
  width: {
    type: String,
    default: '360px'
  },
  size: {
    type: String,
    default: 'default',
    validator: (value) => ['large', 'default', 'small'].includes(value)
  }
});

const emit = defineEmits(["update:modelValue"]);
const { isMobile } = useMobileDetection();

// 计算移动端宽度
const mobileWidth = computed(() => {
  const parentWidth = props.width;
  const numericWidth = parseInt(parentWidth);
  const unit = parentWidth.replace(numericWidth.toString(), '');
  return `${Math.floor((numericWidth - 20) / 2)}${unit}`;
});

// 日期范围选择器的值
const dateRange = ref(null);
// 单个日期选择器的值
const singleDate = ref(null);
// 移动端开始日期
const startDate = ref(null);
// 移动端结束日期
const endDate = ref(null);

// 监听 modelValue 变化
watch(
  () => props.modelValue,
  (newValue) => {
    if (props.isRange) {
      if (Array.isArray(newValue)) {
        const now = dayjs();
        const endTimestamp = newValue[1];
        const endDate = dayjs(endTimestamp);

        // 判断结束时间戳是否是今天的某个时刻（非00:00:00）
        // 如果是今天且不是00:00:00，说明是今天-5分钟的时间戳，不需要减1天
        const isTodayEndTime = endDate.isSame(now, 'day') &&
          (endDate.hour() !== 0 || endDate.minute() !== 0 || endDate.second() !== 0);

        const displayEndValue = props.isMonthPicker
          ? endTimestamp
          : (isTodayEndTime ? endTimestamp : dayjs(endTimestamp).subtract(1, 'day').valueOf());

        dateRange.value = [newValue[0], displayEndValue];
        startDate.value = newValue[0];
        endDate.value = displayEndValue;
      } else {
        dateRange.value = null;
        startDate.value = null;
        endDate.value = null;
      }
    } else {
      singleDate.value = newValue;
    }
  },
  { immediate: true }
);

// 禁用日期的处理函数
const disabledDate = (time) => {
  const currentDate = dayjs();
  const selectedDate = dayjs(time);

  // 禁用所有未来的日期（但不包括今天）
  if (selectedDate.isAfter(currentDate, props.isMonthPicker ? 'month' : 'day')) {
    return true;
  }

  // 添加最大日期限制
  if (props.maxDate && selectedDate.isAfter(dayjs(props.maxDate), props.isMonthPicker ? 'month' : 'day')) {
    return true;
  }

  // 添加最小日期限制
  if (props.minDate && selectedDate.isBefore(dayjs(props.minDate), props.isMonthPicker ? 'month' : 'day')) {
    return true;
  }

  return false;
};

// 获取时间范围时间戳
const getTimeRangeTimestamp = (date, isEnd = false) => {
  const dayjsDate = dayjs(date);
  const now = dayjs();

  // 如果选择的日期超过当前时间，则使用当天开始时间
  if (dayjsDate.isAfter(now, props.isMonthPicker ? 'month' : 'day')) {
    return now.startOf('day').valueOf();
  }

  if (props.isMonthPicker) {
    if (isEnd) {
      // 如果是当前月份，返回当前时间往前推5分钟
      if (dayjsDate.isSame(now, 'month')) {
        return now.subtract(5, 'minute').valueOf();
      }
      return dayjsDate.add(1, 'month').startOf('month').valueOf();
    } else {
      return dayjsDate.startOf('month').valueOf();
    }
  } else {
    if (isEnd) {
      // 如果是当天，返回当前时间往前推5分钟
      if (dayjsDate.isSame(now, 'day')) {
        return now.subtract(5, 'minute').valueOf();
      }
      return dayjsDate.add(1, 'day').startOf('day').valueOf();
    } else {
      return dayjsDate.startOf('day').valueOf();
    }
  }
};

// 处理日期范围变化
const handleDateRangeChange = (val) => {
  if (!val || val.length !== 2) {
    dateRange.value = null;
    startDate.value = null;
    endDate.value = null;
    return;
  }

  let [start, end] = val;

  const daysDiff = props.isMonthPicker
    ? dayjs(end).diff(dayjs(start), "month") + 1
    : dayjs(end).diff(dayjs(start), "day") + 1;

  if (daysDiff > props.maxDays) {
    ElMessage.error(`日期范围不能超过 ${props.maxDays} 天`);
    dateRange.value = null;
    startDate.value = null;
    endDate.value = null;
    return;
  }

  if (daysDiff < props.minDays) {
    ElMessage.error(`日期范围不能小于 ${props.minDays} 天`);
    dateRange.value = null;
    startDate.value = null;
    endDate.value = null;
    return;
  }

  const adjustedStart = getTimeRangeTimestamp(start, false);
  const adjustedEnd = getTimeRangeTimestamp(end, true);

  emit("update:modelValue", [adjustedStart, adjustedEnd]);
};

// 处理单个日期变化
const handleSingleDateChange = (val) => {
  if (!val) {
    singleDate.value = null;
    return;
  }

  if (props.isMonthPicker) {
    const start = getTimeRangeTimestamp(val, false);
    const end = getTimeRangeTimestamp(val, true);
    emit("update:modelValue", [start, end]);
  } else {
    const adjustedDate = getTimeRangeTimestamp(val, false);
    emit("update:modelValue", adjustedDate);
  }
};

// 处理移动端开始日期变化
const handleMobileStartDateChange = (val) => {
  if (!val) {
    startDate.value = null;
    if (!endDate.value) {
      return;
    }
    return;
  }

  if (endDate.value) {
    const adjustedStart = getTimeRangeTimestamp(val, false);
    const adjustedEnd = getTimeRangeTimestamp(endDate.value, true);

    const daysDiff = props.isMonthPicker
      ? dayjs(endDate.value).diff(dayjs(val), "month") + 1
      : dayjs(endDate.value).diff(dayjs(val), "day") + 1;

    if (daysDiff > props.maxDays) {
      ElMessage.error(`日期范围不能超过 ${props.maxDays} 天`);
      startDate.value = null;
      return;
    }

    if (daysDiff < props.minDays) {
      ElMessage.error(`日期范围不能小于 ${props.minDays} 天`);
      startDate.value = null;
      return;
    }

    emit("update:modelValue", [adjustedStart, adjustedEnd]);
  }
};

// 处理移动端结束日期变化
const handleMobileEndDateChange = (val) => {
  if (!val) {
    endDate.value = null;
    if (!startDate.value) {
      return;
    }
    return;
  }

  if (startDate.value) {
    const adjustedStart = getTimeRangeTimestamp(startDate.value, false);
    const adjustedEnd = getTimeRangeTimestamp(val, true);

    const daysDiff = props.isMonthPicker
      ? dayjs(val).diff(dayjs(startDate.value), "month") + 1
      : dayjs(val).diff(dayjs(startDate.value), "day") + 1;

    if (daysDiff > props.maxDays) {
      ElMessage.error(`日期范围不能超过 ${props.maxDays} 天`);
      endDate.value = null;
      return;
    }

    if (daysDiff < props.minDays) {
      ElMessage.error(`日期范围不能小于 ${props.minDays} 天`);
      endDate.value = null;
      return;
    }

    emit("update:modelValue", [adjustedStart, adjustedEnd]);
  }
};
</script>

<style scoped>
.filter-header {
  display: flex;
  align-items: center;
  gap: 1rem;
  flex-wrap: nowrap;
}

.filter-header--mobile {
  flex-direction: column;
  align-items: stretch;
  gap: 0.75rem;
}

.date-picker-wrapper {
  flex: 1;
  min-width: 0;
}

.date-picker-wrapper--mobile {
  width: 100%;
}

.mobile-date-picker {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 0.5rem;
  width: 100%;
}

.mobile-date-input {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  min-width: 0;
}

.mobile-date-input :deep(.el-input__wrapper) {
  width: 100%;
}

.separator {
  flex: none;
  color: var(--el-text-color-regular);
  padding: 0 0.5rem;
  white-space: nowrap;
}

:deep(.el-picker__popper) {
  max-width: 90vw;
}
</style>